package com.example.meituan.activity.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;


import com.example.meituan.R;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.CommentBean;
import com.example.meituan.activity.bean.OrderBean;

import com.example.meituan.activity.bean.OrderDetailsBean;
import com.example.meituan.activity.bean.ShopBean;
import com.example.meituan.activity.man.StoreActivity;
import com.example.meituan.activity.user.adapter.UserOrderAdapter;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.dao.CommentDao;
import com.example.meituan.dao.OrderDao;
import com.example.meituan.dao.OrderDetailsDao;
import com.example.meituan.dao.ShopDao;
import com.example.meituan.until.FileImgUntil;


import java.util.List;
import java.util.UUID;

public class UserOrderManageActivity extends AppCompatActivity implements OrderItemClickListener{
    AdminBean user;
    UserOrderAdapter adapter;
    private Uri url;
    private ActivityResultLauncher<String> getContentLauncher;
    //打开文件选择器
    private void openGallery(View v){
        getContentLauncher.launch("image/*");
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_user_order_manage);
        user=AdminDao.getUserInfo(UserOrderManageActivity.this);

        List<OrderBean> orderBeans= OrderDao.getAllOrdersByUserId(user.getUserId());
        androidx.recyclerview.widget.RecyclerView recyclerView=findViewById(R.id.order_recyclerView);
        if (orderBeans == null || orderBeans.isEmpty()) {
            Toast.makeText(this, "没有数据显示", Toast.LENGTH_SHORT).show();
            recyclerView.setAdapter(null);
        } else {
            adapter = new UserOrderAdapter(orderBeans,this); ;
            recyclerView.setAdapter(adapter);
        }
    }

    @Override
    public void onOrderItemClick(OrderBean orderBean) {
        String id=orderBean.getsOrderDetialsId();
        OrderDetailsBean orderDetailsBean= OrderDetailsDao.getOrderDetailById(id);
        ShopBean shopBean= ShopDao.getShopById(orderDetailsBean.getShopId());
        Intent intent=new Intent(UserOrderManageActivity.this, ProductDetialsActivity.class);
        intent.putExtra("shopBean", shopBean);
        startActivity(intent);
    }

    @Override
    public void toStore(OrderBean orderBean) {
        Intent intent=new Intent(UserOrderManageActivity.this, StoreActivity.class);
        intent.putExtra("businessBean",  orderBean.getsBusinessId());
        startActivity(intent);
    }

    @Override
    public void cancleOrder(OrderBean orderBean) {
        AlertDialog.Builder builder = new AlertDialog.Builder(UserOrderManageActivity.this);
        builder.setTitle("确认退款");
        builder.setMessage("确定要申请退款吗？");

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                orderBean.setsOrderSta("取消中");
                OrderDao.updateOrder(orderBean);
            }
        });

        // 创建并显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @Override
    public void confirmOrder(OrderBean orderBean) {

        StringBuilder userDescriptions = new StringBuilder();

        LayoutInflater inflater = LayoutInflater.from(UserOrderManageActivity.this);
        View dialogView = inflater.inflate(R.layout.add_comment, null);

        EditText editTypeDescriptions = dialogView.findViewById(R.id.add_comment_text);
        Button btnSubmit = dialogView.findViewById(R.id.btn_submit);
        editTypeDescriptions.setText(userDescriptions.toString());
        Button btnCancel = dialogView.findViewById(R.id.btn_cancel);
        TextView back=findViewById(R.id.order_back_user);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(UserOrderManageActivity.this);
        builder.setView(dialogView);

        final AlertDialog alertDialog = builder.create();


        btnSubmit.setOnClickListener(view -> {
            OrderDetailsBean orderDetailsBean=OrderDetailsDao.getOrderDetailById(orderBean.getsOrderDetialsId());

            String updatedText = editTypeDescriptions.getText().toString();
            ImageView img=findViewById(R.id.add_comment_photo);

            getContentLauncher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
                        @Override
                        public void onActivityResult(Uri result) {
                            if (result != null) {
                                img.setImageURI(result);
                                url = result;
                            } else {
                                Toast.makeText(UserOrderManageActivity.this, "未选择头像", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

            );

            img.setOnClickListener(new View.OnClickListener() {
                                       @Override
                                       public void onClick(View v) {
                                           //打开手机相册,实现上传图片
                                           openGallery(v);

                                       }
                                   }
            );


            Drawable defaultDrawable= ContextCompat.getDrawable(this,R.drawable.photo);
            Drawable drawable = img.getDrawable();
            boolean isValid=true;
            if (drawable instanceof BitmapDrawable) {
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                if (defaultDrawable != null && bitmap.sameAs(((BitmapDrawable) defaultDrawable).getBitmap())) {
                    Toast.makeText(UserOrderManageActivity.this, "图片不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
            }
            if(updatedText.isEmpty()){
                Toast.makeText(UserOrderManageActivity.this, "评论不能为空", Toast.LENGTH_SHORT).show();
                isValid = false;
            }
            if(isValid){
                String path = FileImgUntil.getImgPath();
                FileImgUntil.saveImageBitmapToFile(url, UserOrderManageActivity.this, path);
                CommentBean commentBean=new CommentBean();
                commentBean.setComment(updatedText);
                commentBean.setUserId(user.getUserId());
                String id= String.valueOf(System.currentTimeMillis());
                commentBean.setId(id);
                commentBean.setShopId(orderDetailsBean.getShopId());
                commentBean.setTypeId(orderDetailsBean.getDetailType());
                commentBean.setImg(path);
                commentBean.setComment(updatedText);
                CommentDao.addComment(commentBean);
            }

            alertDialog.dismiss();
        });

        btnCancel.setOnClickListener(view -> alertDialog.dismiss());

        alertDialog.show();


    }


}